package com.qzyh.esb.egsa.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

/**
 * JWT的token，区分大小写
 */
@ConfigurationProperties(prefix = "config.jwt")
@Component
@Data
public class JwtConfig {

    private String secret;
    private long expire;
    private String header;

    /**
     * 由字符串生成加密key
     *
     * @return
     */
    public SecretKeySpec getKey() {
        return new SecretKeySpec(secret.getBytes(), "HmacSHA256");
    }

    /**
     * 生成token
     * @param subject
     * @return
     */
    public String createToken (String subject){
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);//过期时间 1个小时
        return Jwts.builder()
                .setHeaderParam("alg","HS256")
                .setHeaderParam("type","JWT")
                .setSubject(subject)
                .signWith(getKey(),SignatureAlgorithm.HS256)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .compact();
    }
    /**
     * 获取token中注册信息
     * @param token
     * @return
     */
    public Claims getTokenClaim (String token) {
        try {
            return Jwts.parserBuilder().setSigningKey(getKey()).build().parseClaimsJws(token).getBody();
        }catch (Exception e){
            return null;
        }
    }
    /**
     * 验证token是否过期失效
     * @param expirationTime
     * @return
     */
    public boolean isTokenExpired (Date expirationTime) {
        return expirationTime.before(new Date());
    }

    /**
     * 获取token失效时间
     * @param token
     * @return
     */
    public Date getExpirationDateFromToken(String token) {
        return getTokenClaim(token).getExpiration();
    }
    /**
     * 获取用户名从token中
     */
    public String getUsernameFromToken(String token) {
        return getTokenClaim(token).getSubject();
    }

    /**
     * 获取jwt发布时间
     */
    public Date getIssuedAtDateFromToken(String token) {
        return getTokenClaim(token).getIssuedAt();
    }

    public static void main(String[] args) {
        long time  = new Date().getTime();
        System.out.println(time);
        time = time + 3600*1000;
        System.out.println(time);
        System.out.println(new Date(time));
    }

}
